var _historyTpl   = '';
var _popupContent = '';

function selectedRows () {
    var ids  = new Array();
    var rows = Ext.select('tr.trSelected', false, 'memberlist').elements;
    Ext.each(rows, function(r){
        ids.push(Ext.fly(r).down('td div').dom.innerHTML);
    });

    if (ids.length == 0) {
        return 0;
    } else if (ids.length == 1) {
        return ids[0];
    }

    return ids;
} // selectedRows

function populate (data) {
    Ext.each(data, function(d){
        var f = Ext.get(d.f);

        if (f) {
            if (f.dom.type == 'text' || f.dom.type == 'textarea' || f.dom.type == 'hidden') {
                f.dom.value = d.v;
            } else if (f.dom.type == 'select-one') {
                var i = 0;
                Ext.each(f.dom.options, function(o){
                    if (o.value == d.v) {
                        f.dom.options.selectedIndex = i;
                    }
                    i++;
                });
            }

            if (d.f == 'transfer_bank') {
                switchForm();
            }
        }
    });
} // populate

function addnew () {
    openPopup('registration-wrap', 'Add New Member');
    Ext.fly('upline_leg').addClass('req');
} // addnew

function editRecord (id) {
    var mesg = Ext.get('popup-message');

    if (!id) {
        message('Record Id not found.');
        return;
    }

    openPopup('registration-wrap', 'Edit Member Info');
    Ext.fly('upline_leg').removeClass('req');
    Ext.fly('print').show();

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/members/get/'+id,
        method: 'GET',
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            if (obj.status == 1) {
                populate(obj.data);
            } else if (obj.mesg) {
                mesg.update(obj.mesg);
                mesg.addClass('error').highlight();
            }
        },
        failure: function(response, opts) {
            message('server-side failure with status code '+response.status);
        },
        callback: function() {
            Ext.fly('popup-progress').ghost('b', { useDisplay:true });
            Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-registration'), function(e){ e.disabled = false; });
        }
    });

    if (Ext.Ajax.isLoading(transId)) {
        Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-registration'), function(e){ e.disabled = true; });
        Ext.fly('popup-progress').update('Loading..');
        Ext.fly('popup-progress').fadeIn();
    }
} // editRecord

function updateRecord (act) {
    var ids = selectedRows();
    var act = act.toLowerCase();

    if (!ids) {
        message('Please select the row that want to '+act+'.');
        return;
    }
    if (Ext.isArray(ids)) {
        var id = ids.join(',');
    } else {
        var id = ids;
    }

    var mesg = Ext.isArray(ids) ? 'these '+ids.length+' selected records' : 'this selected record';
    if (!confirm('Are you sure you want to '+act+' '+mesg+'?')) {
        return;
    }

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/members/update_status/',
        method: 'POST',
        params: 'id='+id+'&task='+act,
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            if (obj.status == 1) {
                reload_grid();
            } else if (obj.error) {
                message(obj.error);
            }
        },
        failure: function(response, opts) {
            message('server-side failure with status code '+response.status);
        },
        callback: function() {

        }
    });
} // updateRecord

function changeStatus (id, type) {
    var elem = Ext.get(id+'-'+type);
    var curr = elem.dom.className;
    var status = '';

    if (type == 1) {
        if (curr == 'yes') { // from enable login to disable
            status = 'disable';
        } else { // from disable login to enable
            status = 'enable';
        }
    } else {
        if (curr == 'yes') { // from enable trade to disable
            status = 'suspend';
        } else { // from disable trade to enable
            if (Ext.fly(id+'-1').hasClass('no')) { // login disabled, can't enable trade also
                return;
            }
            status = 'enable';
        }
    }

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/members/admin_update_status/',
        method: 'POST',
        params: 'id='+id+'&task='+status,
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            elem.fadeIn();

            if (obj.status == 1) {
                if (curr == 'yes') {
                    elem.removeClass('yes').addClass('no');
                    elem.highlight();

                    if (type == 1) {
                        Ext.fly(id+'-2').highlight().removeClass('yes').addClass('no');
                    }
                } else {
                    elem.removeClass('no').addClass('yes');
                    elem.highlight();

                    if (type == 1) {
                        Ext.fly(id+'-2').highlight().removeClass('no').addClass('yes');
                    }
                }
            } else if (obj.error) {
                message(obj.error);
            }
        },
        failure: function(response, opts) {
            elem.fadeIn();
            message('server-side failure with status code '+response.status);
        }
    });

    if (Ext.Ajax.isLoading(transId)) {
        elem.fadeOut({ useDisplay:true });
    }
} // changeStatus

function openPopup (el, title) {
    clearPopup();

    _popupContent = el;

    Ext.fly('popup-title').update(title);
    Ext.fly(el).show();
    Ext.get('popup').setStyle({
        top: '8px',
        left: '380px'
    }).syncFx().slideIn().fadeIn({ duration:0.8});
} // openPopup

function closePopup () {
    Ext.fly('popup').ghost('b', {
        useDisplay: true,
        callback: clearPopup
    });
    Ext.select('tr.trSelected', false, 'memberlist').removeClass('trSelected');
} // closePopup

function clearPopup () {
    Ext.select('div.popup_content{display!=none}', false, 'popup_content').setStyle({ display:'none' });
    Ext.fly('popup-message').hide();
    Ext.fly('print').hide();
    clearForm();
} // clearPopup

function clearForm () {
    if (_popupContent) {
        Ext.select('.invalid', false, _popupContent).removeClass('invalid');
        Ext.select('div.invalidField', false, _popupContent).remove();
        Ext.select('td.invalidText', false, _popupContent).removeClass('invalidText');

        Ext.each(Ext.query('select option:first-child', 'form-pos'), function(e){ e.selected = true; });
        Ext.each(Ext.query('input.input, input[type=hidden], textarea.input', _popupContent), function(e){ e.value = '' });
        Ext.each(Ext.query('input.date', _popupContent), function(e){ e.value = 'select..' });
        _popupContent = '';
    }
} // clearForm

function init_grid () {
    $("#memberlist").flexigrid({
        url: _webroot+'/admin/members/listData',
        dataType: 'json',
        colModel: [
            { display: 'ID', name: 'id', width: 40, sortable: true, align: 'right' },
            { display: 'International ID', name: 'international_id', width: 60, sortable: true, align: 'left' },
            { display: 'Company Name', name: 'company_name', width: 120, sortable: true, align: 'left', hide: true },
            { display: 'Business Reg No', name: 'company_reg_no', width: 85, sortable: true, align: 'left', hide: true },
            { display: 'Fullname', name: 'fullname', width: 120, sortable: true, align: 'left' },
            { display: 'DOB', name: 'dob', width: 53, sortable: true, align: 'left' },
            { display: 'Identity', name: 'identity', width: 78, sortable: true, align: 'left' },
            { display: 'Residential Address', name: 'residential_address', width: 150, sortable: true, align: 'left', hide: true },
            { display: 'Residential Postcode', name: 'residential_postcode', width: 96, sortable: true, align: 'left', hide: true },
            { display: 'Postal Address', name: 'postal_address', width: 150, sortable: true, align: 'left', hide: true },
            { display: 'Postal Postcode', name: 'postal_postcode', width: 96, sortable: true, align: 'left', hide: true },
            { display: 'Country', name: 'country', width: 40, sortable: true, align: 'left', hide: true },
            { display: 'Email', name: 'email', width: 88, sortable: true, align: 'left' },
            { display: 'Password', name: 'password', width: 60, sortable: true, align: 'left', hide: true },
            { display: 'Telephone', name: 'telephone', width: 60, sortable: true, align: 'left', hide: true },
            { display: 'Mobile', name: 'mobile', width: 60, sortable: true, align: 'left' },
            { display: 'BV', name: 'bv', width: 36, sortable: true, align: 'right' },
            { display: 'Refund Times', name: 'refund_times', width: 65, sortable: true, align: 'right', hide: true },
            { display: 'Status', name: 'status', width: 52, sortable: true, align: 'left' },
            { display: 'Transfer Bank', name: 'transfer_bank', width: 70, sortable: true, align: 'left', hide: true },
            { display: 'Bank', name: 'bank', width: 100, sortable: true, align: 'left', hide: true },
            { display: 'Branch', name: 'branch', width: 100, sortable: true, align: 'left', hide: true },
            { display: 'Bank Account', name: 'bank_account', width: 75, sortable: true, align: 'left', hide: true },
            { display: 'Receiver Name', name: 'receiver_name', width: 120, sortable: true, align: 'left', hide: true },
            { display: 'Receiver Telephone', name: 'receiver_telephone', width: 60, sortable: false, align: 'left', hide: true },
            { display: 'Tree Level', name: 'tree_level', width: 55, sortable: false, align: 'center', hide: true },
            { display: 'Login Times', name: 'login_times', width: 65, sortable: true, align: 'right', hide: true },
            { display: 'Last Login Date', name: 'last_login_time', width: 100, sortable: true, align: 'center', hide: true },
            { display: 'Join Date', name: 'join_date', width: 100, sortable: true, align: 'center' },
            { display: 'Renew Date', name: 'renew_date', width: 100, sortable: true, align: 'center' },
            { display: 'Creation', name: 'created', width: 100, sortable: true, align: 'center', hide: true },
            { display: 'Date Modified', name: 'modified', width: 100, sortable: true, align: 'center', hide: true },
            { display: 'Act', name: 'actions', width: 20, align: 'center' }
        ],
        buttons: [
            { name: 'Add', bclass: 'add', onpress: addnew },
            { separator: true },
            { name: 'Delete', bclass: 'delete', onpress: updateRecord },
            { separator: true }
        ],
        searchitems: [
            { display: 'ID', name: 'id' },
            { display: 'International ID', name: 'international_id', isdefault: true },
            { display: 'Company Name', name: 'company_name' },
            { display: 'Full Name', name: 'fullname' },
            { display: 'Full Name (deleted)', name: 'fullname2' },
            { display: 'ID / Passport No', name: 'identity' },
            { display: 'Country', name: 'country' },
            { display: 'Email', name: 'email' },
            { display: 'Mobile No', name: 'mobile' }
        ],
        sortname: 'id',
        sortorder: 'asc',
        usepager: true,
        title: 'Members',
        useRp: true,
        rp: 15,
        showTableToggleBtn: true,
        width: 970,
        height: 300
    });
} // init_grid

function init_ac () {
    var options = {
        minChars: 1,
        max: 12,
        autoFill: false,
        mustMatch: true,
        matchContains: false,
        width: 260,
        scrollHeight: 260,
        formatItem: function(row) {
            return row[1]+' ('+row[2]+') '+row[3];
        },
        formatResult: function(row) {
            if (typeof(row[1]) == 'undefined') {
                return;
            }
            return row[1].replace(/(<.+?>)/gi, '');
        }
    };

    //$("#member_id").autocomplete(_webroot+'/admin/members/search/', options);
    //$("#sponsor_id").autocomplete(_webroot+'/admin/members/search/', options);
    $("#country").autocomplete(_countries, {
        minChars: 1,
        max: 12,
        autoFill: true,
        mustMatch: true,
        matchContains: false,
        scrollHeight: 260
    });
} // init_ac

function init_calendar () {
    // %H:%M:%S
    var date1 = Calendar.setup({
        inputField: 'join_date',
        trigger: 'join-date',
        dateFormat: '%Y/%m/%d', align: 'Br', showTime: false, minuteStep: 1,
        onSelect: function(date1) {
            var date = date1.selection.print('%a, %e %B %Y');
            if (date.length > 0) {
                Ext.fly('join-date').dom.value = date.join('');
            }
            date1.hide();
        }
    });
    var date2 = Calendar.setup({
        inputField: 'renew_date',
        trigger: 'renew-date',
        dateFormat: '%Y/%m/%d', align: 'Br', showTime: false, minuteStep: 1,
        onSelect: function(date2) {
            var date = date2.selection.print('%a, %e %B %Y');
            if (date.length > 0) {
                Ext.fly('renew-date').dom.value = date.join('');
            }
            date2.hide();
        }
    });
    var date3 = Calendar.setup({
        inputField: 'dob',
        trigger: 'dob-date',
        dateFormat: '%Y/%m/%d', align: 'Br', showTime: false, minuteStep: 1,
        onSelect: function(date3) {
            var date = date3.selection.print('%a, %e %B %Y');
            if (date.length > 0) {
                Ext.fly('dob-date').dom.value = date.join('');
            }
            date3.hide();
        }
    });

    $("#join_time").clockpick({
        starthour: 0,
        endhour: 23,
        minutedivisions: 12,
        event: 'focus',
        layout: 'horizontal'
    });
    $("#renew_time").clockpick({
        starthour: 0,
        endhour: 23,
        minutedivisions: 12,
        event: 'focus',
        layout: 'horizontal'
    });
} // init_calendar

function init_form () {
    Ext.fly('residential_address').on('keyup', function(e, t){
        Ext.fly('postal_address').dom.value = t.value;
    });
    Ext.fly('residential_postcode').on('keyup', function(e, t){
        Ext.fly('postal_postcode').dom.value = t.value;
    });
    Ext.fly('postal_address').on('focus', function(e, t){
        t.select();
    });
} // init_form

function reload_grid () {
    $("#memberlist").flexReload();
} // reload_grid

function save () {
    var proceed = true;
    var transId = '';
    var focuson = '';
    var message = Ext.get('popup-message');

    message.setStyle({ display:'none' });
    Ext.select('.invalid', false, 'form-registration').removeClass('invalid');
    Ext.select('div.invalidField', false, 'form-registration').remove();
    Ext.select('td.invalidText', false, 'form-registration').removeClass('invalidText');
    Ext.each(Ext.select('.req', false, 'form-registration').elements, function(e){
        var el = Ext.get(e);

        if (!el.getValue() || el.getValue() == 'select..') {
            proceed = false;
            el.addClass('invalid');
            el.up('td').prev('td').addClass('invalidText');
            if (!focuson) {
                focuson = e.id;
                el.focus();
                el.fadeIn({
                    duration: 2.0
                });
            }
        }
    });

    if (!proceed) {
        return false;
    }

    transId = Ext.Ajax.request({
        form: 'form-registration',
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);
            if (obj.status == false) {
                if (obj.mesg) {
                    message.update(obj.mesg);
                    message.addClass('error').highlight();
                }
                if (Ext.isArray(obj.error)) {
                    Ext.each(obj.error, function(e) {
                        var el  = Ext.get(e.id);
                        var err = '<div class="invalidField" style="display:none;">'+e.code+'</div>';
                        el.addClass('invalid');
                        el.up('td').prev('td').addClass('invalidText');
                        el.insertHtml('afterEnd', err);
                        el.next('div.invalidField').slideIn('t', {
                            duration:.4
                        });
                        if (!focuson) {
                            focuson = e.id;
                            el.focus();
                            el.fadeIn({
                                duration: 2.0
                            });
                        }
                    });
                }
            } else {
                if (obj.mesg) {
                    if (Ext.fly('id').getValue()) { // update current, close popup
                        setTimeout(closePopup, 3000);
                    } else { // add new, clear form
                        clearForm();
                    }

                    message.update(obj.mesg);
                    message.removeClass('error').addClass('success').highlight();
                    message.pause(8).fadeOut({ useDisplay:true });
                    reload_grid();
                }
            }
        },
        failure: function(response, opts) {
            console.log('server-side failure with status code '+response.status);
        },
        callback: function() {
            Ext.fly('popup-progress').ghost('b', { useDisplay:true });
            Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-registration'), function(e){ e.disabled = false; });
        }
    });

    if (Ext.Ajax.isLoading(transId)) {
        Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-registration'), function(e){ e.disabled = true; });
        Ext.fly('popup-progress').update('Saving..');
        Ext.fly('popup-progress').fadeIn();
    }

    return false;
} // save

function switchForm () {
    if (Ext.fly('transfer_bank').getValue() == '1') {
        var wrap = Ext.get('bank-table');
        if (!wrap.isVisible()) {
            wrap.slideIn();
        }
        Ext.select('.req2', false, 'form-registration').addClass('req');
        Ext.each(Ext.query('input, select', 'bank-table'), function(e){
            e.disabled = false;
        });
    } else {
        Ext.fly('bank-table').slideOut('t', {
            useDisplay: true
        });
        Ext.select('.req2', false, 'form-registration').removeClass('req');
        Ext.each(Ext.query('input, select', 'bank-table'), function(e){
            e.disabled = true;
        });
    }
} // switchForm

function printMember () {
    window.open(_webroot+'/admin/members/print/'+Ext.fly('id').getValue(), 'Member Details', 'width=1, height=1, resize=0, toolbar=0, location=0, scrollbars=0, status=0');
} // printMember

function message (msg, focus) {
    alert(msg);

    if (typeof focus != 'undefined') {
        Ext.fly(focus).focus();
    }
} // message

function init (){
    init_grid();
    init_ac();
    init_calendar();
    init_form();
    switchForm();
}// init